import Vue from 'vue'
import VueRouter from 'vue-router'


Vue.use(VueRouter)

const routes = [
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue')
  },
  // 创建路由规则
  {
    path:'/login',
    name:'login',
    component:()=>import('../views/Login.vue')
  },
  {
    path:'/',
    name:'layout',
    meta:{
      title:'首页'
    },
    component:()=>import('../views/Layout.vue'),
    // 嵌套路由
    children:[
      {
        path:'/users',
        name:'users',
        meta:{
          title:'用户管理'
        },
        component:()=>import('../views/Users.vue')
      },
      {
        path:'/rights',
        name:'rights',
        meta:{
          title:'权限管理'
        },
        component:()=>import('../views/Rights.vue')
      },
      {
        path:'/roles',
        name:'roles',
        meta:{
          title:'角色管理'
        },
        component:()=>import('../views/Roles.vue')
      },
    ]
  },
  
]

const router = new VueRouter({
  routes
})
// 路由导航守卫
router.beforeEach((to,from,next)=>{
  if(to.path=='/login') return next()
  // 获取缓存中的token
  let token = localStorage.getItem('admin_token')
  if (!token) return next('/login') 
  next()

  // to:要访问的路径
  // from:来路
  // next()放行
  

  //后置守卫
  router.afterEach((to,from)=>{
    console.log(to.meta.title);
    document.title=to.meta.title
    localStorage.setItem('title',document.title)
  })
  

})

export default router
